﻿using System;
using System.Collections.Generic;

using RexToy.DesignPattern;
using RexToy.UI.WinForm.ViewModel;

namespace RexToy.UI.WinForm
{
    //TODO:implement, add thread safety etc, more check?
    public class EventBroadcaster : Singleton<EventBroadcaster>
    {
        private Dictionary<string, List<IEventSubscriber>> _subs;
        private EventBroadcaster()
        {
            _subs = new Dictionary<string, List<IEventSubscriber>>();
        }

        public void Subscribe(string evt, IEventSubscriber subscriber)
        {
            if (_subs.ContainsKey(evt))
                _subs[evt].Add(subscriber);
            else
            {
                var list = new List<IEventSubscriber>();
                list.Add(subscriber);
                _subs[evt] = list;
            }
        }

        public void Unsubscribe(string evt, IEventSubscriber subscriber)
        {
            if (_subs.ContainsKey(evt))
                _subs[evt].Remove(subscriber);
            //warning?
        }

        public void Publish(string evt, object sender, BroadcastEventArgs args)
        {
            if (_subs.ContainsKey(evt))
            {
                foreach (var sub in _subs[evt])
                    sub.EventNotify(sender, args);
            }
            //warning???
        }
    }
}
